package models

import (
	"github.com/astaxie/beego/orm"
)

type DsrFlowContent struct {
	Id           int64
	Call_id      string
	Content      string
	Record_path  string
	Record_base  string
	Callee       string
	Caller       string
	Dsr_time     string
	Fine         string
	Fail         string
	Speak_second int
}

const flowContentSql = "dsr_flow_content"
const failkeySql = "fail_keys"
const finekeySql = "fine_keys"
const successkeySql = "success_keys"

//flow_content获取列表，根据cdrId
func FlowContentGetListByCdrId(page, pageSize int, callid, other_uuid string) ([]*DsrFlowContent, int64) {

	offset := (page - 1) * pageSize
	list := make([]*DsrFlowContent, 0)
	cond := orm.NewCondition()
	cond1 := cond.And("call_id__exact", callid).Or("call_id__exact", other_uuid)
	query := orm.NewOrm().QueryTable(flowContentSql).SetCond(cond1)

	total, _ := query.Count()
	var err error
	if page == -1 {
		_, err = query.OrderBy("id").All(&list)
	} else {
		_, err = query.OrderBy("id").Limit(pageSize, offset).All(&list)
	}
	if err != nil {
		ErrorLog(err)
	}
	return list, total

}

func AiFlowContentGetListAll(orderby string, filters ...interface{}) ([]*DsrFlowContent, int64) {
	list := make([]*DsrFlowContent, 0)
	query := orm.NewOrm().QueryTable(flowContentSql)
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy(orderby).All(&list)

	return list, total
}

func SelectCallPgCdr(uuid string) (string, error) {
	sqlStr := "SELECT record_file FROM call_pg_cdr WHERE uuid='" + uuid + "'"
	var record_file string
	err := orm.NewOrm().Raw(sqlStr).QueryRow(&record_file)
	if err != nil {
		ErrorLog(err)
		return err.Error(), err
	}
	return record_file, nil
}

func AiFlowContentGetWeixian() ([]*FailKeys) {
	list := make([]*FailKeys, 0)
	query := orm.NewOrm().QueryTable(failkeySql)
	query.All(&list)

	return list
}

func AiFlowContentGetYouliang() ([]*FineKeys) {
	list := make([]*FineKeys, 0)
	query := orm.NewOrm().QueryTable(finekeySql)
	query.All(&list)

	return list
}

func AiFlowContentGetSuccess() ([]*SuccessKeys) {
	list := make([]*SuccessKeys, 0)
	query := orm.NewOrm().QueryTable(successkeySql)
	query.All(&list)

	return list
}

func AiGetKeyword(content string) (error, string, string) {
	sqlStr := "select keyword from fail_keys WHERE  '" + content + "' ~ keyword;"
	sqlStr1 := "select keyword from fine_keys WHERE  '" + content + "' ~ keyword;"
	var fail string
	var fine string
	var failKeysArr []string
	var fineKeysArr []string
	_, err := orm.NewOrm().Raw(sqlStr).QueryRows(&failKeysArr)
	_, err = orm.NewOrm().Raw(sqlStr1).QueryRows(&fineKeysArr)
	for _, v := range failKeysArr {
		fail += v + ","
	}
	for _, v := range fineKeysArr {
		fine += v + ","
	}
	if err != nil {
		ErrorLog(err)
		return err, "", ""
	}
	return nil, fail, fine
}
